﻿using System;
using System.Web.Optimization;

namespace Blog1._0
{
    /// <summary>
    /// 混淆加密js的类
    /// 实现IBundleTransform接口并实现方法Process(要处理的javascript的源码就在Process方法中)
    /// </summary>
    public class CustomJsMinify : IBundleTransform
    {
        public void Process(BundleContext context, BundleResponse response)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            if (!context.EnableInstrumentation)
            {
                try
                {
                    //response.Content = "/*\r\nAuthor:Emrys\r\nVerson:1.1\r\n*/\r\n" + response.Content;
                    //最后一个参数为false，防止生成混淆代码时候特殊因特殊词出错
                    ECMAScriptPacker p = new ECMAScriptPacker(ECMAScriptPacker.PackerEncoding.Normal, true, false);
                    response.Content = p.Pack(response.Content);
                }
                catch (Exception ex)
                {
                    response.Content = "/*\r\nError:" + ex.Message + "\r\n*/\r\n" + response.Content;
                }
            }
            response.ContentType = "text/javascript";
        }
    }
}